﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef REALMD_REALMDSYSTEM_H_
#define REALMD_REALMDSYSTEM_H_

#include <ctime>
#include <boost/unordered_map.hpp>
#include "Shared/DB/DB.h"
#include "Shared/Base/Event.h"
#include "Shared/Base/Mutex.h"
#include "Shared/Net/TcpServer.h"
#include "Shared/Util/SubSystem.h"
#include "Realmd/RealmList.h"
#include "Realmd/Net/AuthSocketHandler.h"


class RealmdSystem: public Shared::Util::SubSystem
{
public:
	RealmdSystem(void);
	virtual ~RealmdSystem(void);

	virtual bool initialize(void);
	virtual void run(void);
	virtual void uninitialize(void);
	virtual void onSignal(int signal);

    Shared::Database& loginDB(void) { return _loginDB; }
    RealmList& realmList(void) { return _realmList; }


    bool addUnauthedSocket(int id, AuthSocketHandler *sock);
    bool moveSocketAuthed(int id);

private:
    void updateUnauthedSocket(void);
    void updateAuthedSockets(void);
    void closeSockets(void);


    Shared::Database _loginDB;
    int _loginDBPingTime;
    Shared::Net::TcpServer _NetServer;

    RealmList _realmList;
    int _realmListUpdateTime;
    
    Shared::Event _stopEvent;
    volatile bool _running;

    ///////////////////////////////////////////////////////////////////////////
    typedef boost::unordered_map<int, AuthSocketHandler*> UnauthedSocketMap;
    typedef boost::unordered_map<std::uint32_t, AuthSocketHandler*> AuthedSocketMap;

    time_t _maxAuthTime;
    UnauthedSocketMap _unAuthedSockets;
    AuthedSocketMap _authedSockets;
    AuthedSocketMap _closingSockets;
    Shared::Mutex _unAuthedSocketsLock;
    Shared::Mutex _authedSocketsLock;
};

#endif /* REALMD_REALMDSYSTEM_H_ */
